package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//匹配所有拦截路径
@Slf4j
@WebFilter("/*")
public class ReggieFilter implements Filter {
    private static final AntPathMatcher MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        获取请求的pattern URI
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();

//        判断是否需要拦截
        //定义放行匹配路径
        String[] pattern = {
                "/backend/**",
//                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/user/login",
                "/user/loginout",
                "/user/sendMsg"
        };

//        匹配拦截规则
//
//        静态资源以及登录退出请求放行
        boolean match = match(MATCHER,pattern,uri);
        if(match){
            filterChain.doFilter(request,response);
            return;
        }

//        不匹配判断session是否存在
        Long employeeId = (Long) request.getSession().getAttribute("employeeId");
        if(employeeId != null){

//          通过threadLocal存储employeeID
            BaseContext.setCurrentData(employeeId);


            filterChain.doFilter(request,response);
            return;
        }

//
//        Long userId = (Long) request.getSession().getAttribute("userId");
//        if(userId != null){
//
//            BaseContext.setCurrentData(userId);
//            filterChain.doFilter(request,response);
//            return;
//        }




//      非登陆状态&&请求资源
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }


    private boolean match(AntPathMatcher matcher,String[] urls,String path){
        for (String url : urls) {
            boolean match = matcher.match(url, path);
            if(match){
                return match;
            }
        }
        return false;
    }
}
